package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    /**
     * 根据id删除分类,删除之前需要判断分类里,有没有东西
     * @param id
     */
    @Override
    public void remove(Long id) {
        log.info("删除分类,id为:{}",id);
          //添加查询条件,根据分类id进行查询菜品数据
        LambdaQueryWrapper<Dish> dqw = new LambdaQueryWrapper<>();
         dqw.eq(Dish::getCategoryId,id);
         //查询菜肴表  count 聚合函数 查询表里总共有多少数据
        int count1 = dishService.count(dqw);
         //如果分类 和 菜肴列表已经关联 抛出异常.
        if(count1>0){
            throw new BusinessException("当前分类下关联了菜品,不能删除");
        }


        //查询当前分类,是否关联了套餐,如果已经关联,排斥异常
        LambdaQueryWrapper<Setmeal> sqw = new LambdaQueryWrapper<>();
        sqw.eq(Setmeal::getCategoryId,id);
        //查询套餐表  count 聚合函数 查询表里总共有多少数据
        int count2 = setmealService.count(sqw);
        if(count2>0){
            throw new BusinessException("当前分类下关联了套餐,不能删除");
        }
        //正常删除分类
        super.removeById(id);
    }
}
